package com.jthink.admin.page;

import java.util.Date;

import com.jthink.common.model.SinglePage;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

/**
 * 单页管理业务
 */
public class PageAdminService {
	private static int pageSize = 25;
	private SinglePage dao = new SinglePage().dao();

	/**
	 * 分页
	 */
	public Page<SinglePage> paginate(int pageNumber) {
		return dao.paginate(pageNumber, pageSize, "select *", "from single_page order by updated desc");
	}

	/**
	 * 搜索
	 */
	public Page<SinglePage> search(String key, int pageNumber) {
		String sql = "select * from single_page where title like concat('%', #para(0), '%') order by updated desc";
		return dao.templateByString(sql, key).paginate(pageNumber, pageSize);
	}

	private Ret validate(SinglePage SinglePage) {
		if (SinglePage == null) {
			return Ret.fail( "SinglePage 对象不能为 null");
		}
		if (StrKit.isBlank(SinglePage.getTitle())) {
			return Ret.fail( "title 不能为空");
		}
		if (StrKit.isBlank(SinglePage.getContent())) {
			return Ret.fail( "content 不能为空");
		}
		return null;
	}

	/**
	 * 创建
	 */
	public Ret save(int accountId, SinglePage SinglePage) {
		Ret ret = validate(SinglePage);
		if (ret != null) {
			return ret;
		}

		SinglePage.setAccountId(accountId);
		SinglePage.setState(SinglePage.STATE_UNPUBLISHED); // 默认未发布
		SinglePage.setCreated(new Date());
		SinglePage.setUpdated(SinglePage.getCreated());
		SinglePage.setViewCount(0);
		SinglePage.save();
		return Ret.ok( "创建成功");
	}

	/**
	 * 更新
	 */
	public Ret update(SinglePage SinglePage) {
		Ret ret = validate(SinglePage);
		if (ret != null) {
			return ret;
		}

		SinglePage.setUpdated(new Date());
		SinglePage.update();
		return Ret.ok( "更新成功");
	}

	/**
	 * 发布
	 */
	public Ret publish(int id, boolean checked) {
		int state = checked ? SinglePage.STATE_PUBLISHED : SinglePage.STATE_UNPUBLISHED;
		String sql = "update single_page set state = ? where id = ?";
		Db.update(sql, state, id);
		return Ret.ok();
	}

	/**
	 * 获取
	 */
	public SinglePage getById(int id) {
		return dao.findById(id);
	}

	/**
	 * 删除
	 */
	public Ret deleteById(int id) {
		dao.deleteById(id);
		return Ret.ok( "删除成功");
	}
}
